package com.robot.base.base.vm

import android.app.Application
import android.bluetooth.BluetoothGattCharacteristic
import android.util.Log
import androidx.databinding.ObservableField
import cn.wandersnail.ble.BleSppGattAttributes
import cn.wandersnail.ble.Connection
import cn.wandersnail.ble.RequestBuilderFactory
import cn.wandersnail.ble.WriteOptions
import com.robot.base.util.ActivityUtils
import com.robot.base.view.TipDialog
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.*
import me.goldze.mvvmhabit.base.BaseModel
import me.goldze.mvvmhabit.base.BaseViewModel
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import java.util.*

/**
 * 创建日期：2020/9/14  12:18
 * 类说明:
 *
 * @author：robot
 */
open class GLBaseViewModel(application: Application) : BaseViewModel<BaseModel>(application) {
    private val mDisposables: CompositeDisposable? = CompositeDisposable()
    protected var loadingDialog: TipDialog? = null

    /**
     * 是否已识别
     */
    var isDifference = ObservableField<Boolean>();

    fun addNetworkRequest(d: Disposable?) {
        mDisposables!!.add(d!!)
    }

    override fun onDestroy() {
        super.onDestroy()
        mDisposables?.clear()
    }

    fun showLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog!!.dismiss()
            loadingDialog = null
        }
        loadingDialog = TipDialog.Builder(ActivityUtils.getTopActivity())
                .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create()
        loadingDialog?.show()
    }

    fun dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            loadingDialog!!.dismiss()
        }
    }

    var finishCommand = BindingCommand<Any>(BindingAction {
        finish()
    })


    /**
     * 发送
     *
     * @param bytes
     */
    @Synchronized
    fun sendData(bytes: ByteArray?, connect: Connection?) {
        if (connect == null) {
            return
        }
        CoroutineScope(Dispatchers.Main).launch {
            withContext(Dispatchers.IO){
                delay(50)
            }
            Log.d("EasyBLE", "开始写入")
            val builder =
                RequestBuilderFactory().getWriteCharacteristicBuilder(
                    UUID.fromString(BleSppGattAttributes.BLE_SPP_Service),
                    UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic), bytes!!
                )
            //根据需要设置写入配置
            val writeType = if (connect.hasProperty(
                    UUID.fromString(BleSppGattAttributes.BLE_SPP_Service),
                    UUID.fromString(BleSppGattAttributes.BLE_SPP_Write_Characteristic),
                    BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
                )
            ) BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE else BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
            builder.setWriteOptions(
                WriteOptions.Builder()
                    .setPackageSize(connect.mtu - 3)
                    .setPackageWriteDelayMillis(5)
                    .setRequestWriteDelayMillis(10)
                    .setWaitWriteResult(true)
                    .setWriteType(writeType)
                    .build()
            )
            //不设置回调，使用观察者模式接收结果
            builder.build().execute(connect)
        }
    }

}